package demo;

import javax.servlet.http.*;
import javax.servlet.*;

import java.util.logging.Logger;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

public class UserServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(UserServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		UserAO ao = new UserAO();
		List<User> phonelist = ao.getAllphoneno();
		String authentication;
		String phoneno = req.getParameter("phoneno");
		String passcode = req.getParameter("passcode");
		PrintWriter out = resp.getWriter();

		if (phoneno.trim().length() == 0 || passcode.trim().length() == 0) {

			out.println("<html><body onLoad=\"alert('Field cannot be blank');window.location.href='Login.html';\"></html>");
			// resp.sendRedirect("http://mytrack102.appspot.com/LoginTry.html");
		} else {
			if (phoneno.trim().length() < 8 || passcode.trim().length() < 4) {
				out.println("<html><body onLoad=\"alert('Invalid field entered');window.location.href='Login.html';\"></html>");
			} else {
				if (phonelist.contains(phoneno)) {
					String apasscode = ao.getaPasscode(phoneno);

					if (apasscode.equals(passcode)) {
						authentication = ao
								.getAuthentication(phoneno, passcode);
						String[] a = authentication.split(",");
						String imei = a[0];
						String role = a[1];

						if (role.equals("admin")) {
							req.getRequestDispatcher("adminindex.html").forward(req,resp);

						} else {

							 HttpSession session = req.getSession(true);
							 session.setAttribute("imei", imei);
							 req.getRequestDispatcher("index.html").forward(req,resp);
						}

					} else {
						out.println("<html><body onLoad=\"alert('Wrong passcode entered');window.location.href='Login.html';\"></html>");
					}
				} else {
					out.println("<html><body onLoad=\"alert('Invalid account !');window.location.href='Login.html';\"></html>");
				}
			}
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		doGet(req, resp);
	}

}
